package com.jack;

import com.jack.utils.ImageUtils;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 *
 * @author jack
 * @ user canvas here to receive key events.
 */
public class CounterCanvas extends Canvas implements CommandListener {

    private HomeworkMidlet midlet;
    private Command backCommand;
    private Command okCommand;
    private Command clearCommand;
    private Command helpCommand;
    private Command fullScreenCommand;
    private Command keepScaleCommand;
    private Command showImageCommand;
    private Command closeScreenCommand;
    private Command lightCommand;
    private CounterItem counterItem;
    int width = getWidth();
    int height = getHeight();
    Alert errorAlert = new Alert("错误", "", null, AlertType.INFO);
    Vector vector;
    boolean fullScreen = false;
    boolean keepScale = true;
    boolean showImage = false;
    boolean closeScreen = false;
    boolean light = false;

    public CounterCanvas(final HomeworkMidlet midlet) {
        this.midlet = midlet;
        backCommand = new Command("返回", Command.BACK, 1);
        okCommand = new Command("增加", Command.OK, 0);
        clearCommand = new Command("清零", Command.ITEM, 0);
        fullScreenCommand = new Command("全屏显示", Command.ITEM, 1);
        showImageCommand = new Command("显示图片", Command.ITEM, 2);
        keepScaleCommand = new Command("保持比例", Command.ITEM, 3);
        helpCommand = new Command("帮助", Command.ITEM, 4);
        closeScreenCommand = new Command("关闭屏幕", Command.ITEM, 5);
        lightCommand = new Command("照明", Command.ITEM, 6);

        addCommand(backCommand);
        addCommand(okCommand);
        //addCommand(clearCommand);
        //addCommand(helpCommand);
        addCommand(fullScreenCommand);
        addCommand(showImageCommand);
        addCommand(keepScaleCommand);
        addCommand(closeScreenCommand);
        addCommand(lightCommand);

        setCommandListener(this);

        if (counterItem != null) {
            fullScreen = counterItem.isFullSceenMode();
            setFullScreenMode(fullScreen);
        }
    }
    private int x = width / 2;
    private int y = height / 2;
    private int baseY = 5;
    private Font font = Font.getDefaultFont();

    protected void paint(Graphics g) {
        if (closeScreen) {
            g.setColor(0x000000);
            g.fillRect(0, 0, width, height);
            return;
        }
        if (light) {
            g.setColor(0xffffff);
            g.fillRect(0, 0, width, height);
            return;
        }

        g.setColor(counterItem.getBackColor());
        g.fillRect(0, 0, width, height);
        g.setColor(counterItem.getForeColor());

        drawImage(g);

        //draw counter
        g.drawString(String.valueOf(counterItem.getCounter()), (width / 2), height - 2, Graphics.BOTTOM | Graphics.HCENTER);
    }

    protected void sizeChanged(int w, int h) {
        this.width = w;
        this.height = h;
        initDrawingImage();
    }
    Image srcImage;
    Image drawingImage;

    private boolean imagePathExists() {
        String imagePath = counterItem.getImagePath();
        if (imagePath != null && !"".equals(imagePath) && !" ".equals(imagePath)) {
            return true;
        } else {
            return false;
        }
    }

    private void initSourceImage() {
        try {
            String imagePath = counterItem.getImagePath();
            if (srcImage == null && imagePathExists()) {
                srcImage = Image.createImage(Class.class.getResourceAsStream(imagePath));
            }

        } catch (Exception ex) {
            midlet.log(ex);
        }
    }

    private void initDrawingImage() {
        try {
            if (!imagePathExists()) {
                return;
            }
            if (srcImage == null) {
                initSourceImage();
            }

            int iw = srcImage.getWidth();
            int ih = srcImage.getHeight();
            int destw = width;
            int desth = height;

            float srcRite = 1.0f * iw / ih;

            //if (counterItem.isKeepScale()) {
            if (keepScale) {
                if (desth <= destw / srcRite) {
                    destw = (int) (desth * srcRite);
                } else {
                    desth = (int) (1.0f * destw / srcRite);
                }
            }

            if (desth == ih && destw == iw) {
                drawingImage = srcImage;
            } else {
                midlet.log("image-w: " + iw + " image-h: " + ih + " rate: " + srcRite);
                midlet.log("screen-w: " + width + " screen-h: " + height);
                midlet.log("dest-w: " + destw + " dest-h: " + desth);
                drawingImage = ImageUtils.transImageOffScreen(srcImage, destw, desth);
            }

        } catch (Exception ex) {
            midlet.log(ex);
        }
    }

    private void drawImage(Graphics g) {
        try {
            if (showImage && imagePathExists()) {

                int margin = 0;

                if (drawingImage == null) {
                    initDrawingImage();
                }
                if (drawingImage != null) {
                    g.drawImage(drawingImage, width / 2, margin, Graphics.HCENTER | Graphics.TOP);
                }

            }
        } catch (Exception ex) {
            midlet.log(ex);
        }
    }

    private void addCounter() {
        counterItem.Add();
    }

    private void clearCounter() {
        counterItem.Clear();
    }

    public void keyPressed(int keyCode) {
        char tempChar = Character.toLowerCase((char) keyCode);
        Character pressedKey = new Character(tempChar);

        int gameAction = getGameAction(keyCode);
        int gameKeyIntValue = 'A' + gameAction;
        Character gameKey = new Character((char) gameKeyIntValue);
        if (counterItem.isAnyKeyCount()
                || vector.contains(pressedKey)
                || vector.contains(gameKey)) {
            addCounter();
            repaint();
        }
    }

    /**
     * @return the counterItem
     */
    public CounterItem getCounterItem() {
        return counterItem;
    }

    /**
     * @param counterItem the counterItem to set
     */
    public void setCounterItem(CounterItem counterItem) {
        this.counterItem = counterItem;
        setTitle(counterItem.getName());
        vector = counterItem.getCountKeysVector(':');

        this.showImage = counterItem.isShowImage();
        this.fullScreen = counterItem.isFullSceenMode();
        this.keepScale = counterItem.isKeepScale();

        setFullScreenMode(counterItem.isFullSceenMode());

        srcImage = null;
        drawingImage = null;
        initDrawingImage();
    }

    public void commandAction(Command c, Displayable d) {
        try {
            if (c == backCommand) {
                midlet.saveCounter(counterItem);
                midlet.makeCurrent();
            } else if (c == okCommand) {
                addCounter();
                repaint();
            } else if (c == clearCommand) {
                // clear currentCounter
                clearCounter();
                midlet.saveCounter(counterItem);
                repaint();
            } else if (c == helpCommand) {
                showHelp();
            } else if (c == fullScreenCommand) {
                fullScreen = !fullScreen;
                closeScreen = false;
                light = false;
                setFullScreenMode(fullScreen);
                repaint();
            } else if (c == showImageCommand) {
                showImage = !showImage;
                repaint();
            } else if (c == keepScaleCommand) {
                keepScale = !keepScale;
                closeScreen = false;
                light = false;
                initDrawingImage();
                repaint();
            } else if (c == closeScreenCommand) {
                closeScreen = !closeScreen;
                light = false;
                setFullScreenMode(closeScreen);
                repaint();
            } else if (c == lightCommand) {
                light = !light;
                closeScreen = false;
                setFullScreenMode(light);
                repaint();
            }
        } catch (Exception ex) {
            midlet.log(ex);
        }
    }

    private void showAbout() {
        Alert aboutAlert = new Alert("关于", "这是一个计数器程序。", null,
                AlertType.INFO);
        aboutAlert.setTimeout(Alert.FOREVER);
        midlet.display.setCurrent(aboutAlert);
    }

    private void showHelp() {
        Alert helpAlert = new Alert("帮助", "按任意键增加计数。", null,
                AlertType.INFO);
        helpAlert.setTimeout(Alert.FOREVER);
        midlet.display.setCurrent(helpAlert);
    }
}
